package com.shop.user;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
public class UserDaoImpl implements UserDao{

    private static final int FIXED_PAGE_SIZE = 10; // 固定每页10条
    private final UserMapper usermapper;
    private final Snowflake snowflake;

    @Autowired
    public UserDaoImpl(UserMapper userMapper) {
        this.usermapper = userMapper;
        // 初始化雪花算法，参数1为workerId，参数2为dataCenterId
        // 可以根据实际分布式环境配置，单机应用可以使用默认值
        this.snowflake = IdUtil.getSnowflake(1, 1);
    }

    @Override
    public List<User> findAll() {
        return usermapper.findAll();
    }

    @Override
    public List<User> findPage(int pageNumber) {
        // 获取所有数据
        List<User> allUsers = usermapper.findAll();

        // 使用 Hutool 的 PageUtil 进行分页
        int[] startEnd = PageUtil.transToStartEnd(pageNumber - 1, FIXED_PAGE_SIZE);
        int fromIndex = startEnd[0];
        int toIndex = Math.min(startEnd[1], allUsers.size());

        return allUsers.subList(fromIndex, toIndex);
    }

    @Override
    public User findByUserid(Long userid) {
        return usermapper.findByUserid(userid);
    }

    @Override
    public User findByUsername(String username) {
        return usermapper.findByUsername(username);
    }

    @Override
    public User findByEmail(String email) {
        return usermapper.findByEmail(email);
    }

    @Override
    public int insertUser(User user) {
        // 如果userid为空，使用雪花算法生成
        if (user.getUserid() == null) {
            user.setUserid(snowflake.nextId());
        }

        // 设置创建时间为当前时间
        if (user.getCreatedDt() == null) {
            user.setCreatedDt(new Date());
        }

        return usermapper.insertUser(user);
    }

    @Override
    public int updateUser(User user) {
        // 设置更新时间
        user.setUpdatedDt(new Date());
        return usermapper.updateUser(user);
    }

    @Override
    public int deleteUser(Long userid) {
        return usermapper.deleteUser(userid);
    }
}
